﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.Threading;
using System.IO;

namespace AzureDriverExplorer_Client
{
    /// <summary>
    /// Interaction logic for Page.xaml
    /// </summary>
    public partial class Paste : Window
    {
        private int TryCase = 0;
        private int TryCancel = 0;
        private Const cons = new Const();
        private System.Resources.ResourceManager ResManager;
        private Comm comm = new Comm();

        public Paste(List<string> FilePath, string NewPath)
        {
            InitializeComponent();
            // icon設定
            this.Icon = this._GetIconSource("logoicon2");
            AddConnectionLanguage();
            //Progress名を入れます
            System.Threading.Thread thread = new System.Threading.Thread(new System.Threading.ThreadStart(delegate()
            {
                int count = 0;
                foreach (string path in FilePath)
                {
                    bool valide = true;
                    bool Error = false;

                    this.labOrigin.Dispatcher.Invoke(System.Windows.Threading.DispatcherPriority.Normal, new Action(delegate()
                            {
                                this.labOrigin.Content = ResManager.GetString("Origin" + cons.Language) + ": " + path;
                            }));

                    this.labDestiny.Dispatcher.Invoke(System.Windows.Threading.DispatcherPriority.Normal, new Action(delegate()
                            {
                                this.labDestiny.Content = ResManager.GetString("Destiny" + cons.Language) + ": " + NewPath + System.IO.Path.GetFileName(path);
                            }));
                    System.Threading.Thread.Sleep(1000);


                    while (valide == true)
                    {
                        if (Valide(path))
                        {
                            valide = false;
                        }
                        else

                            if (MessageBox.Show(ResManager.GetString("Error_NotExist" + cons.Language) + Environment.NewLine + ResManager.GetString("Info_TryAgain" + cons.Language), string.Empty, MessageBoxButton.YesNo, MessageBoxImage.Question) != MessageBoxResult.Yes)
                            {
                                valide = false;
                                Error = true;
                            }
                    }

                    if (!Error)
                    {

                        if (Valide(NewPath + System.IO.Path.GetFileName(path)))
                        {
                            Initializer(path, NewPath, ResManager.GetString("Error_Exist" + cons.Language));
                        }
                        else // if not have file in direcction destine
                        {
                            valide = true;
                            Error = false;
                            while (valide == true)
                            {
                                string Textresult = Copy(path, NewPath + System.IO.Path.GetFileName(path));
                                if (Textresult.Equals(string.Empty))
                                {
                                    valide = false;
                                }
                                else
                                {
                                    if (Initializer(path, NewPath, Textresult))
                                        valide = false;
                                }
                            }
                        }

                        this.AllFile.Dispatcher.Invoke(System.Windows.Threading.DispatcherPriority.Normal, new Action(delegate()
                        {
                            if (this.AllFile.IsChecked != true)
                                TryCase = 0;

                        }));

                        //Cancel
                        if (TryCancel == 1)
                            break;


                    }

                    progressBar1.Dispatcher.Invoke(System.Windows.Threading.DispatcherPriority.Normal, new Action(delegate()
                    {
                        progressBar1.Value = ((int)count * 100 / FilePath.Count);
                    }));
                    System.Threading.Thread.Sleep(100);
                    count++;
                }

                this.Dispatcher.Invoke(System.Windows.Threading.DispatcherPriority.Normal, new Action(delegate()
                    {
                        this.DialogResult = true;
                        this.Close();
                    }));


            }));
            thread.Start();

        }

        private void AddConnectionLanguage()
        {

            ResManager = new System.Resources.ResourceManager("AzureDriverExplorer_Client.Properties.Resources", this.GetType().Assembly);

            this.Title = ResManager.GetString("Paste" + cons.Language).Trim();
            labOrigin.Content = ResManager.GetString("Origin" + cons.Language).Trim();
            labDestiny.Content = ResManager.GetString("Destiny" + cons.Language).Trim();

            ReplaceName.Content = ResManager.GetString("Replace" + cons.Language).Trim();
            Change.Content = ResManager.GetString("Change" + cons.Language).Trim();
            Past.Content = ResManager.GetString("Past" + cons.Language).Trim();
            Cancel.Content = ResManager.GetString("Cancel" + cons.Language).Trim();
        }

        private bool Initializer(string path, string NewPath, string error)
        {

            this.Options.Dispatcher.Invoke(System.Windows.Threading.DispatcherPriority.Normal, new Action(delegate()
            {
                if (TryCase == 0)
                    this.Options.Visibility = Visibility.Visible;
            }));

            bool valide = true;
            //bool Error = false;
            if (TryCase == 0)
                while (valide == true)
                {
                    this.labInfo.Dispatcher.Invoke(System.Windows.Threading.DispatcherPriority.Normal, new Action(delegate()
                    {
                        this.labInfo.Content = error;
                        this.labInfo.Visibility = Visibility.Visible;
                    }));

                    if (TryCase != 0)
                    {
                        valide = false;
                        //Error = true;
                    }

                }

            this.Options.Dispatcher.Invoke(System.Windows.Threading.DispatcherPriority.Normal, new Action(delegate()
            {
                this.Options.Visibility = Visibility.Collapsed;
            }));

            this.labInfo.Dispatcher.Invoke(System.Windows.Threading.DispatcherPriority.Normal, new Action(delegate()
            {
                this.labInfo.Content = "";
                this.labInfo.Visibility = Visibility.Collapsed;
            }));



            if (TryCase == 1)
            {
                valide = true;
                //Error = false;
                while (valide == true)
                {
                    string Textresult = Replace(path, NewPath + System.IO.Path.GetFileName(path));

                    if (Textresult.Equals(string.Empty))
                    {
                        valide = false;
                        return true;
                    }
                    else
                        if (MessageBox.Show(Textresult + Environment.NewLine + ResManager.GetString("Info_TryAgain" + cons.Language), string.Empty, MessageBoxButton.YesNo, MessageBoxImage.Question) != MessageBoxResult.Yes)
                        {
                            valide = false;
                            //Error = true;
                        }
                }

            }
            else if (TryCase == 2)
            {
                valide = true;
                //Error = false;
                while (valide == true)
                {
                    string Textresult = Rename(path, NewPath, System.IO.Path.GetFileName(path));

                    if (Textresult.Equals(string.Empty))
                    {
                        valide = false;
                        return true;
                    }
                    else
                        if (MessageBox.Show(Textresult + Environment.NewLine + ResManager.GetString("Info_TryAgain" + cons.Language), string.Empty, MessageBoxButton.YesNo, MessageBoxImage.Question) != MessageBoxResult.Yes)
                        {
                            valide = false;
                            // Error = true;
                        }
                }

            }
            else if (TryCase == 3)
            {
                return true;
            }
            else if (TryCase == 4)
            {
                TryCancel = 1;
                return true;
            }

            return true;

        }


        protected bool Valide(string path)
        {
            try
            {
                if (System.IO.Path.GetExtension(path).Equals(string.Empty))
                {
                    return Directory.Exists(path);
                }
                else
                    return File.Exists(path);
            }
            catch
            {
                return false;
            }
        }


        protected string Copy(string path, string NewPath)
        {
            try
            {
                if (System.IO.Path.GetExtension(path).Equals(string.Empty))
                {
                    if (!Directory.Exists(NewPath))
                    Directory.CreateDirectory(NewPath);

                    List<string> files = new List<string>();
                    files = comm.GetFileTheAllDirectory(path);

                    // Copy the files and overwrite destination files if they already exist.
                    foreach (string s in files)
                    {
                        // Use static Path methods to extract only the file name from the path.
                        
                        string destFile = System.IO.Path.Combine(NewPath, s);
                        string Temppath = System.IO.Path.GetDirectoryName(destFile);
                        if (!Directory.Exists(Temppath))
                            Directory.CreateDirectory(Temppath);

                        System.IO.File.Copy(path + (path.EndsWith(@"\")?string.Empty:@"\")+s, destFile, true);
                    }

                }
                else
                {


                    File.Copy(path, NewPath, true);
                }
                return string.Empty;
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }

        protected string Replace(string path, string NewPath)
        {
            try
            {
                if (System.IO.Path.GetExtension(path).Equals(string.Empty))
                {
                    if (!Directory.Exists(NewPath))
                        Directory.CreateDirectory(NewPath);

                    List<string> files = new List<string>();
                    files = comm.GetFileTheAllDirectory(path);

                    // Copy the files and overwrite destination files if they already exist.
                    foreach (string s in files)
                    {
                        // Use static Path methods to extract only the file name from the path.

                        string destFile = System.IO.Path.Combine(NewPath, s);
                        string Temppath = System.IO.Path.GetDirectoryName(destFile);
                        if (!Directory.Exists(Temppath))
                            Directory.CreateDirectory(Temppath);

                        System.IO.File.Copy(path + (path.EndsWith(@"\") ? string.Empty : @"\") + s, destFile, true);
                    }

                }
                else
                {
                    File.Copy(path, NewPath, true);
                    
                }
                return string.Empty;
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }

        /// <summary>
        /// 移動前、ファイル名をチェックします
        /// </summary> 
        private string Rename(string oldPath, string newPath, string FileName)
        {
            try
            {
                if (System.IO.Path.GetExtension(oldPath).Equals(string.Empty))
                {

                    if (Directory.Exists(newPath))
                    {
                        newPath += FileName+" - " + DateTime.Now.ToString("yyyy-MM-dd HH-mm-ss");
                        Directory.CreateDirectory(newPath);
                    }
                    List<string> files = new List<string>();
                    files = comm.GetFileTheAllDirectory(oldPath);

                    // Copy the files and overwrite destination files if they already exist.
                    foreach (string s in files)
                    {
                        // Use static Path methods to extract only the file name from the path.

                        string destFile = System.IO.Path.Combine(newPath, s);
                        string Temppath = System.IO.Path.GetDirectoryName(destFile);
                        if (!Directory.Exists(Temppath))
                            Directory.CreateDirectory(Temppath);

                        System.IO.File.Copy(oldPath + (oldPath.EndsWith(@"\") ? string.Empty : @"\") + s, destFile, true);
                    }

                }
                else
                {

                    string NewFileName = string.Empty;
                    if (File.Exists(newPath + FileName))
                    {
                        int cont = 1;
                        string OriginalNameWithoutExt = System.IO.Path.GetFileNameWithoutExtension(FileName);
                        string Ext = System.IO.Path.GetExtension(FileName);

                        while (File.Exists(newPath + FileName) == true)
                        {
                            FileName = OriginalNameWithoutExt + "(" + cont + ")" + Ext;
                            cont++;
                        }

                        File.Copy(oldPath, newPath + FileName);
                    }
                }
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
            return string.Empty;
        }

        /// <summary>
        /// Remplaze
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Button_Click(object sender, RoutedEventArgs e)
        {
            TryCase = 1;
        }
        /// <summary>
        /// Rename
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Button_Click_1(object sender, RoutedEventArgs e)
        {
            TryCase = 2;
        }

        /// <summary>
        /// Omition
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Button_Click_2(object sender, RoutedEventArgs e)
        {
            TryCase = 3;
        }

        /// <summary>
        /// Cancel
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Button_Click_3(object sender, RoutedEventArgs e)
        {
            TryCase = 4;
        }


        private ImageSource _GetIconSource(string iconName)
        {
            Stream iconstm = this._MakeIconStream(iconName);
            IconBitmapDecoder icon = new IconBitmapDecoder(iconstm, BitmapCreateOptions.None, BitmapCacheOption.Default);
            return icon.Frames[0];
        }

        private Stream _MakeIconStream(string name)
        {
            System.Drawing.Icon icon = null;
            switch (name)
            {
                case "Private.ico":
                    icon = Properties.Resources.Private;
                    break;
                case "CloseFolder.ico":
                    icon = Properties.Resources.CloseFolder;
                    break;
                case "OpenFolder.ico":
                    icon = Properties.Resources.OpenFolder;
                    break;
                case "logoicon2":
                    icon = Properties.Resources.logoicon2;
                    break;
            }

            MemoryStream stm = new MemoryStream();
            icon.Save(stm);


            return stm;
        }

    }
}
